package com.springboot.demo.io.socketmultiplex;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 多路复用器线程，一个线程绑定一个selector
 *
 * @author supu
 * @since 2020-11-12 17:32
 **/
public class SelectorThread extends ThreadLocal<LinkedBlockingQueue<Channel>> implements Runnable {

    /**
     * 多路复用器
     */
    Selector selector;

    /**
     * 多路复用器所在的线程组
     */
    SelectorThreadGroup selectorThreadGroup;

    LinkedBlockingQueue<Channel> channelQueue;

    @Override
    protected LinkedBlockingQueue<Channel> initialValue() {
        return new LinkedBlockingQueue<>();
    }

    public SelectorThread(SelectorThreadGroup selectorThreadGroup) {
        try {
            this.selectorThreadGroup = selectorThreadGroup;

            channelQueue = get();

            // 获取多路复用器，例如 select 、poll 和 epoll
            selector = Selector.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                // 获取所有有状态的fd列表，这里会发生阻塞
                int fdNum = selector.select();
                if (fdNum > 0) {
                    // 有事件处理
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isAcceptable()) {
                            // 接收客户端事件
                            acceptHandler(key);
                        } else if (key.isReadable()) {
                            // 读事件
                            readHandler(key);
                        } else if (key.isWritable()) {
                            // 写事件
                            writeHandler(key);
                        }
                    }

                }

                // 处理 listen 的 client 的 注册事件
                if (!channelQueue.isEmpty()) {
                    Channel channel = channelQueue.poll();
                    if (channel instanceof ServerSocketChannel) {
                        // socket 服务端注册
                        ServerSocketChannel server = (ServerSocketChannel) channel;
                        server.register(selector, SelectionKey.OP_ACCEPT);
                    } else {
                        // client 注册
                        SocketChannel server = (SocketChannel) channel;
                        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
                        server.register(selector, SelectionKey.OP_READ, byteBuffer);
                    }

                    System.out.println(getThreadName() + " register listen");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void writeHandler(SelectionKey key) {}

    private void readHandler(SelectionKey key) {
        ByteBuffer buffer = (ByteBuffer) key.attachment();
        SocketChannel client = (SocketChannel) key.channel();
        buffer.clear();

        while (true) {
            try {
                int read = client.read(buffer);
                if (read > 0) {
                    // 存在数据，处理数据
                    buffer.flip();
                    if (buffer.hasRemaining()) {
                        byte[] bytes = new byte[buffer.limit()];
                        buffer.get(bytes);

                        System.out.println(getThreadName() + " receive data ：" + new String(bytes));
                    }
                    buffer.clear();
                } else if (read == 0) {
                    break;
                } else {
                    key.cancel();
                    break;
                }

            } catch (IOException e) {
                key.cancel();
                break;
            }
        }
    }

    private void acceptHandler(SelectionKey key) {
        try {
            // 获取 channel，并接收 channel
            ServerSocketChannel channel = (ServerSocketChannel) key.channel();
            SocketChannel client = channel.accept();

            // 设置非阻塞模式
            client.configureBlocking(false);

            System.out.println(getThreadName() + " accept client ：" + client.getRemoteAddress());

            // 注册到多路复用器上，具体注册到哪个 selector ，根据负载均衡算法来实现
            selectorThreadGroup.registerSelector(client);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getThreadName() {
        return Thread.currentThread().getName();
    }
}
